﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace linkouqs.Gamekit {

    public class CharacterInput : MonoBehaviour {

        [SerializeField] KeyCode m_JumpKeyCode = KeyCode.W;
        [SerializeField] KeyCode m_RunLeftKeyCode = KeyCode.A;
        [SerializeField] KeyCode m_RunRightKeyCode = KeyCode.D;
        [SerializeField] KeyCode m_ActionKeyCode = KeyCode.S;
       

        [Range(0.01f, 1f)] [SerializeField] float m_HorizontalChangeDuraction = 1f;

        public bool IsPressedJump { get; private set; }

        public bool IsPressedRun { get; private set; }
        public bool IsPressedRunLeft { get; private set; }
        public bool IsPressedRunRight { get; private set; }

        public bool IsPressedAction { get; private set; }

        public bool IsRunLeft { get { return Horizontal < 0f; } }
        public bool IsRunRight { get { return Horizontal > 0f; } }

        public float Horizontal { get; private set; }
        public float HorizontalChangeSpeed { get; private set; }
        public float HorizontalChangeDuraction { get { return m_HorizontalChangeDuraction; } }


        void Awake() {
            CaculateHorizontalChangeSpeed();

            CharacterController2D controller2D = GetComponent<CharacterController2D>();
            if (controller2D != null) {

                /// TODO.
                /// 
                /// 读取角色按键
                /// 

            }
        }

        void CaculateHorizontalChangeSpeed() {
            HorizontalChangeSpeed = 1 / m_HorizontalChangeDuraction;
        }

        void FixedUpdate() {

#if UNITY_EDITOR
            CaculateHorizontalChangeSpeed();
#endif

            IsPressedJump = Input.GetKey(m_JumpKeyCode);
            IsPressedRunLeft = Input.GetKey(m_RunLeftKeyCode);
            IsPressedRunRight = Input.GetKey(m_RunRightKeyCode);
            IsPressedRun = IsPressedRunLeft || IsPressedRunRight;
            IsPressedAction = Input.GetKey(m_ActionKeyCode);
           

            if (IsPressedRunLeft && !IsPressedRunRight) {
                Horizontal = Mathf.Clamp(Horizontal - HorizontalChangeSpeed * Time.deltaTime, -1, 0);
            } else if (!IsPressedRunLeft && IsPressedRunRight) {
                Horizontal = Mathf.Clamp(Horizontal + HorizontalChangeSpeed * Time.deltaTime, 0, 1);
            } else {
                if (Horizontal > 0) {
                    Horizontal = Mathf.Clamp(Horizontal - HorizontalChangeSpeed * Time.deltaTime, 0, 1);
                } else if (Horizontal < 0) {
                    Horizontal = Mathf.Clamp(Horizontal + HorizontalChangeSpeed * Time.deltaTime, -1, 0);
                }
            }

            

            

        }

        public void ResetHorizontal() {
            Horizontal = 0f;
        }

    }

}
